home *** CD-ROM | disk | FTP | other *** search
- Path: newsfeed.internetmci.com!iol!usenet
- From: "John D. Hourihane" <hourihaj@iol.ie>
- Newsgroups: comp.lang.c
- Subject: Can a function return a (pointer to a) function?
- Date: 26 Jan 1996 19:33:30 GMT
- Organization: Ireland On-Line
- Message-ID: <4ebaaa$jh6@barnacle.iol.ie>
- NNTP-Posting-Host: dialup-158.dublin.iol.ie
-
- Hello world,
-
- I am trying to write a function which will return a pointer to a function,
- but I'm having no luck.
-
- The toy program below illustrates (I hope) what I want to be able to do,
- but as it stands it won't compile for me. The idea is that the call to
- '(pick(ADD))' will return a pointer to the 'add' function which is then
- dereferenced and used.
-
- But like I say, it doesn't compile. It complains 'Declaration terminated
- incorrectly' as I declare 'pick'. I'm using Turbo C/C++.
-
- Any reply, posted here or by email, would be great.
-
- PHiL
-
- /* The toy program, to use a function that returns a
- * pointer to a function.
- */
-
- #include <stdio.h>
-
- #define ADD 0
- #define MULTIPLY 1
-
- int add(int x, int y);
- int multiply(int x, int y);
-
- /* pick returns a pointer to a function which will operate on two integers */
- (int f(int, int)) *pick(int s);
-
- int main()
- {
- printf("5 + 4 = %d\n", (*(pick(ADD)))(5,4));
- printf("5 * 4 = %d\n", (*(pick(MULTIPLY)))(5,4));
- return 0;
- }
-
- int add(int x, int y)
- { return x + y; }
-
- int multiply(int x, int y)
- { return x * y; }
-
- (int f(int, int)) *pick(int s)
- { if (s == ADD)
- return add;
- return multiply;
- }
-